#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
分层匹配算法API - 实现智能匹配、批量计算和匹配推荐
"""

from flask import Blueprint, request, current_app
from app.services.matching_service import MatchingService
from app.services.mate_criteria_service import MateCriteriaService
from app.utils.auth import user_token_required
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required_fields

# 创建蓝图
matching_bp = Blueprint('matching', __name__)

@matching_bp.route('/matching/intelligent-match', methods=['GET', 'POST'])
@user_token_required
def intelligent_match(current_user):
    """智能匹配用户"""
    try:
        if request.method == 'GET':
            # GET方式 - 从查询参数获取
            page = int(request.args.get('page', 1))
            per_page = int(request.args.get('per_page', 20))
            min_score = float(request.args.get('min_score', 60))
            location_priority = request.args.get('location_priority', 'false').lower() == 'true'
            online_recently = request.args.get('online_recently', 'false').lower() == 'true'
            
            filter_options = {
                'min_score': min_score,
                'location_priority': location_priority,
                'online_recently': online_recently
            }
        else:
            # POST方式 - 从JSON数据获取
            data = request.get_json() or {}
            page = data.get('page', 1)
            per_page = data.get('per_page', 20)
            filter_options = data.get('filter_options', {})
        
        # 参数验证
        if per_page > 50:
            per_page = 50
        
        # 调用智能匹配服务
        result = MatchingService.intelligent_match(
            current_user.id, page, per_page, filter_options
        )
        
        if not result['success']:
            return error_response(result['error'], 400)
        
        return success_response(result['data'], '智能匹配完成')
        
    except Exception as e:
        current_app.logger.error(f"智能匹配异常: {str(e)}")
        return error_response(f"匹配失败: {str(e)}", 500)


@matching_bp.route('/matching/batch-calculate', methods=['POST'])
@user_token_required
def batch_calculate_match_scores(current_user):
    """批量计算匹配度"""
    try:
        data = request.get_json() or {}
        user_ids = data.get('user_ids', [])
        algorithm_type = data.get('algorithm_type', 'advanced')
        
        if not user_ids:
            return error_response('用户ID列表不能为空', 400)
        
        if len(user_ids) > 100:  # 限制批量数量
            return error_response('单次最多批量计算100个用户', 400)
        
        # 过滤掉当前用户ID
        user_ids = [uid for uid in user_ids if uid != current_user.id]
        
        if not user_ids:
            return error_response('没有有效的目标用户ID', 400)
        
        # 批量计算匹配度
        result = MatchingService.batch_calculate_match_scores(
            current_user.id, user_ids, algorithm_type
        )
        
        if 'error' in result:
            return error_response(result['error'], 400)
        
        return success_response(result, '批量计算完成')
        
    except Exception as e:
        current_app.logger.error(f"批量计算匹配度异常: {str(e)}")
        return error_response(f"计算失败: {str(e)}", 500)


@matching_bp.route('/matching/recommendations', methods=['GET', 'POST'])
@user_token_required
def generate_match_recommendations(current_user):
    """生成个性化匹配推荐"""
    try:
        if request.method == 'GET':
            # GET方式 - 从查询参数获取
            recommendation_type = request.args.get('recommendation_type', 'daily')
            count = int(request.args.get('count', 10))
            diversity_factor = float(request.args.get('diversity_factor', 0.3))
        else:
            # POST方式 - 从JSON数据获取
            data = request.get_json() or {}
            recommendation_type = data.get('recommendation_type', 'daily')
            count = data.get('count', 10)
            diversity_factor = data.get('diversity_factor', 0.3)
        
        # 参数验证
        if count > 50:
            count = 50
        
        if not 0 <= diversity_factor <= 1:
            return error_response('多样性因子应在0-1之间', 400)
        
        # 生成推荐
        result = MatchingService.generate_match_recommendations(
            current_user.id, recommendation_type, count, diversity_factor
        )
        
        if not result['success']:
            return error_response(result['error'], 400)
        
        return success_response(result['data'], '推荐生成完成')
        
    except Exception as e:
        current_app.logger.error(f"生成推荐异常: {str(e)}")
        return error_response(f"推荐失败: {str(e)}", 500)


@matching_bp.route('/matching/algorithms', methods=['GET'])
@user_token_required
def get_algorithms_info(current_user):
    """获取可用匹配算法信息"""
    try:
        algorithms_info = MatchingService.get_algorithms_info()
        return success_response(algorithms_info, '获取算法信息成功')
        
    except Exception as e:
        current_app.logger.error(f"获取算法信息异常: {str(e)}")
        return error_response(f"获取失败: {str(e)}", 500)


@matching_bp.route('/matching/statistics', methods=['GET'])
@user_token_required
def get_user_matching_statistics(current_user):
    """获取用户匹配统计信息"""
    try:
        statistics = MatchingService.get_user_matching_statistics(current_user.id)
        
        if 'error' in statistics:
            return error_response(statistics['error'], 400)
        
        return success_response(statistics, '获取统计信息成功')
        
    except Exception as e:
        current_app.logger.error(f"获取匹配统计异常: {str(e)}")
        return error_response(f"获取失败: {str(e)}", 500)


@matching_bp.route('/matching/preferences', methods=['GET', 'PUT'])
@user_token_required
def user_matching_preferences(current_user):
    """用户匹配偏好设置"""
    try:
        if request.method == 'GET':
            # 获取当前偏好设置
            preferences = MatchingService.get_user_matching_preferences(current_user.id)
            return success_response(preferences, '获取偏好设置成功')
        
        else:
            # 更新偏好设置
            data = request.get_json() or {}
            
            result = MatchingService.update_user_matching_preferences(
                current_user.id, data
            )
            
            if not result['success']:
                return error_response(result['error'], 400)
            
            return success_response(result['data'], result['message'])
        
    except Exception as e:
        current_app.logger.error(f"匹配偏好设置异常: {str(e)}")
        return error_response(f"操作失败: {str(e)}", 500)


@matching_bp.route('/matching/debug/score-details/<int:target_user_id>', methods=['GET'])
@user_token_required
def get_detailed_match_calculation(target_user_id, current_user):
    """获取详细的匹配分数计算过程（调试用）"""
    try:
        if target_user_id == current_user.id:
            return error_response('不能查看与自己的匹配度详情', 400)
        
        debug_info = MatchingService.get_detailed_match_calculation(
            current_user.id, target_user_id
        )
        
        if 'error' in debug_info:
            return error_response(debug_info['error'], 400)
        
        return success_response(debug_info, '获取调试信息成功')
        
    except Exception as e:
        current_app.logger.error(f"获取调试信息异常: {str(e)}")
        return error_response(f"获取失败: {str(e)}", 500) 